<!--
  @author:  long
  @date:    2023/3/2
  @file:    客户列表
  @require:
-->
<template>
  <div class="commonCustomer app-container">
    <!-- 客户列表主体 start -->
    <div class="px-2">
      <!-- 搜索 start -->
      <avue-form
        :option="queryFormOption"
        v-model="queryForm"
        ref="queryFormRef"
      >
        <!--   客户状态   -->
        <!--        <template #status>-->
        <!--          <el-select-->
        <!--            clearable-->
        <!--            v-model="queryForm.status"-->
        <!--            placeholder="客户状态"-->
        <!--          >-->
        <!--            <el-option-->
        <!--              v-for="(dict, index) in customer_status"-->
        <!--              :label="dict.label"-->
        <!--              :value="dict.value"-->
        <!--              :key="index"-->
        <!--            ></el-option>-->
        <!--          </el-select>-->
        <!--        </template>-->
        <!-- 客户类别 -->
        <template #customerType>
          <el-select
            clearable
            v-model="queryForm.customerType"
            placeholder="客户类别"
          >
            <el-option
              v-for="(dict, index) in customer_class"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </template>
        <!-- 客户星级 -->
        <template #starRating>
          <el-select
            clearable
            v-model="queryForm.starRating"
            placeholder="客户星级"
          >
            <el-option
              v-for="(dict, index) in customer_star"
              :label="dict.label"
              :value="dict.value"
              :key="index"
            ></el-option>
          </el-select>
        </template>
        <!--    更新时间    -->
        <template #updateTime>
          <el-date-picker
            style="width: 100%"
            v-model="updateTime"
            type="daterange"
            start-placeholder="更新时间起"
            end-placeholder="更新时间止"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
          />
        </template>
        <template #menu-form="{}">
          <el-button icon="Search" type="primary" @click="handleQuery"
            >查询
          </el-button>
          <el-button icon="RefreshLeft" @click="handleEmpty">重置</el-button>
          <el-button icon="Filter" link type="primary" @click="openDrawer"
            >高级筛选
          </el-button>
        </template>
      </avue-form>
      <!-- 搜索 end -->

      <!-- 操作按钮 start-->
      <div class="px-2 pb-3 mt-3">
        <el-button
          type="primary"
          icon="Plus"
          plain
          @click="handleOpenDialog('receive')"
        >
          领取客户
        </el-button>
        <!--        <el-button icon="Flag" type="primary" @click="" plain-->
        <!--          >转移客户</el-button-->
        <!--        >-->
      </div>
      <!-- 操作按钮 end-->

      <!--   客户列表显示start   -->
      <el-table
        ref="tableRef"
        :data="tableData"
        border
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @row-dblclick="goDetails"
      >
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column
          label="编号"
          show-overflow-tooltip
          prop="customerNumber"
          align="center"
        >
          <!-- <template #default="scope">
                      <el-button link type="primary" @click="goDetails(scope.row)">{{
                        scope.row.systemNumber
                      }}</el-button>
                    </template> -->
        </el-table-column>
        <el-table-column
          label="客户名称"
          show-overflow-tooltip
          prop="customerName"
        >
          <!-- <template #default="scope">
                      <el-button link type="primary" @click="goDetails(scope.row)">{{
                        scope.row.customerName
                      }}</el-button>
                    </template> -->
        </el-table-column>
        <!--        <el-table-column-->
        <!--          label="客户状态"-->
        <!--          prop="status"-->
        <!--          align="center"-->
        <!--          width="130"-->
        <!--        >-->
        <!--        </el-table-column>-->
        <el-table-column label="客户星级" align="center" width="130">
          <template #default="scope">
            <dict-tag :options="customer_star" :value="scope.row.starRating" />
          </template>
        </el-table-column>

        <el-table-column
          label="首联系人"
          prop="mainContactName"
          align="center"
          width="130"
        ></el-table-column>
        <el-table-column
          label="联系电话"
          prop="mainContactPhone"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          label="最后跟进时间"
          width="160"
          prop="statusUpdateTime"
          align="center"
        ></el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryForm.pageNum"
        v-model:limit="queryForm.pageSize"
        @pagination="getList"
      />
      <!--   客户列表显示end   -->

      <!-- 高级筛选 start -->
      <el-drawer class="p-0" size="50%" v-model="drawer" title="高级筛选">
        <avue-form
          :option="drawerFormOption"
          v-model="queryForm"
          ref="drawerFormRef"
        >
          <template #menu-form="{}">
            <el-button icon="Search" type="primary" @click="handleQuery"
              >查询
            </el-button>
            <el-button icon="RefreshLeft" @click="handleDrawerFormEmpty"
              >重置
            </el-button>
          </template>
          <!--   客户状态   -->
          <!--          <template #status>-->
          <!--            <el-select-->
          <!--              v-model="queryForm.status"-->
          <!--              placeholder="客户状态"-->
          <!--              class="w-full"-->
          <!--              clearable-->
          <!--            >-->
          <!--              <el-option-->
          <!--                v-for="(dict, index) in customer_status"-->
          <!--                :label="dict.label"-->
          <!--                :value="dict.value"-->
          <!--                :key="index"-->
          <!--              ></el-option>-->
          <!--            </el-select>-->
          <!--          </template>-->
          <!-- 行业类型 -->
          <template #industryTypeCode>
            <el-select
              v-model="queryForm.industryTypeCode"
              placeholder="行业类别"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(dict, index) in industry_category"
                :key="index"
                :value="dict.value"
                :label="dict.label"
              ></el-option>
            </el-select>
          </template>
          <!-- 客户类别 -->
          <template #customerType>
            <el-select
              v-model="queryForm.customerType"
              placeholder="客户类别"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(dict, index) in customer_class"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </template>
          <!-- 客户星级 -->
          <template #starRating>
            <el-select
              v-model="queryForm.starRating"
              placeholder="客户星级"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(dict, index) in customer_star"
                :label="dict.label"
                :value="dict.value"
                :key="index"
              ></el-option>
            </el-select>
          </template>
          <!-- 客户来源 -->
          <template #origin>
            <el-select
              v-model="queryForm.origin"
              placeholder="客户来源"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(dict, index) in customer_source"
                :label="dict.label"
                :value="dict.value"
                :key="index"
              ></el-option>
            </el-select>
          </template>
          <!--    更新时间    -->
          <template #updateTime>
            <el-date-picker
              style="width: 100%"
              v-model="updateTime"
              type="daterange"
              start-placeholder="更新时间起"
              end-placeholder="更新时间止"
              format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD"
            />
          </template>
          <!--    归属公司    -->
          <template #orgId>
            <el-tree-select
              style="width: 100%"
              v-model="queryForm.orgId"
              :data="companyOptions"
              clearable
              :props="{
                value: 'id',
                label: 'label',
                children: 'children'
              }"
              placeholder="请选择归属单位"
              value-key="id"
              filterable
            />
          </template>
          <!--    归属人员    -->
          <template #userId>
            <el-select
              v-model="queryForm.userId"
              placeholder="请选择归属人员"
              @focus="userInputFocus"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(item, index) in selectOptionObj['userId']"
                :key="index"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
          </template>
          <!--    归属企业      -->
          <template #parentId>
            <el-select
              v-model="queryForm.parentId"
              placeholder="请选择所属企业"
              class="w-full"
              filterable
              remote
              :remote-method="queryCustomer"
            >
              <el-option
                v-for="item in parentOptions"
                :key="item.id"
                :label="item.customerName"
                :value="item.id"
              >
                <div>
                  <span>{{ item.customerName }}</span>
                  <span>({{ item.mainContactName }})</span>
                </div>
              </el-option>
            </el-select>
          </template>
        </avue-form>
      </el-drawer>
      <!-- 高级筛选 end -->
    </div>
    <!-- 客户列表主体end -->
    <!--  公共弹窗start -->
    <el-dialog
      v-model="dialogObj.visible"
      destroy-on-close
      :close-on-click-modal="false"
      :width="dialogObj.width"
      :title="dialogObj.title"
    >
      <!--      新建任务-->
      <!--      <add-task v-if="dialogObj.model == 'task'" />-->
      <!--  转入公海 -->
      <div v-if="dialogObj.model == 'pool'">
        <div class="flex">
          <div class="w-25">备注信息：</div>
          <div>
            <el-input
              v-model="statusDescription"
              rows="5"
              class="mb-2"
              maxlength="100"
              placeholder="输入内容"
              show-word-limit
              type="textarea"
            />
            <div class="text-xs">
              *转移到公海后此客户数据将属于公共资源，原归属人员不能再维护跟进和更新此客户数据。
            </div>
          </div>
        </div>
      </div>
      <!--    领取客户    -->
      <div v-if="dialogObj.model == 'receive'">
        <div class="text-xl text-slate-950 mb-2 flex items-center">
          <i
            class="i-ph-question mr-1"
            style="font-size: 26px; color: orange"
          ></i>
          <span>是否确认领取所选择的客户？</span>
        </div>
        <div class="ml-12 text-sm text-gray-400">
          领取后N天后未跟进/成交，客户将自动放回公海
        </div>
      </div>

      <!--   底部按钮   -->
      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="dialogSave">保存</el-button>
      </template>
    </el-dialog>
    <!--  公共弹窗end -->
    <!--  弹窗选择组件  -->
    <SelectDialog :dialog-param="dialogParam" @ok="selectData"></SelectDialog>
  </div>
</template>

<script setup name="CommonCustomer">
import { getCurrentInstance, toRaw } from 'vue'
import { useRouter } from 'vue-router'
import SelectDialog from '@/components/SelectDialog/index.vue'
import {
  delCustomer,
  getCustomerList,
  updateForOpenSea
} from '@/api/customerManage/customerList'
import { treeselect } from '@/api/rsgl/zzjg'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const router = useRouter()

const { proxy } = getCurrentInstance()
const drawer = ref(false) //抽屉弹窗
const loading = ref(false)
const data = reactive({
  queryForm: {
    pageNum: 1,
    pageSize: 10,
    status: '8',
    orgId: userStore.user.orgId
  },
  total: 0,
  tableData: [],
  updateTime: [], //更新时间
  // 查询的form表单配置
  queryFormOption: {
    labelWidth: 0,
    menuSpan: 6,
    submitBtn: false,
    emptyBtn: false,
    column: [
      {
        prop: 'customerNameOrNumber',
        placeholder: '客户名称、编号',
        span: 4
      },
      // {
      //   prop: 'status', //客户状态
      //   span: 3
      // },
      {
        prop: 'customerType', //客户类别
        span: 3
      },
      {
        prop: 'starRating', //客户星级
        span: 3
      },
      {
        prop: 'updateTime',
        span: 5
      }
    ]
  },
  //   高级筛选弹窗form表单配置
  drawerFormOption: {
    labelWidth: 80,
    submitBtn: false,
    emptyBtn: false,
    column: [
      {
        label: '客户名称',
        prop: 'customerNameOrNumber',
        placeholder: '客户名称、编号',
        span: 12
      },
      // {
      //   label: '客户状态',
      //   prop: 'status',
      //   span: 12
      // },
      {
        label: '行业类型',
        prop: 'industryTypeCode',
        placeholder: '行业类型',
        span: 12
      },
      {
        label: '客户类别',
        prop: 'customerType',
        placeholder: '客户类别',
        span: 12
      },
      {
        label: '客户星级',
        prop: 'starRating',
        placeholder: '客户星级',
        span: 12
      },
      {
        label: '客户来源',
        prop: 'origin',
        placeholder: '客户来源',
        span: 12
      },
      {
        label: '联系人',
        prop: 'phoneAndNameContact',
        placeholder: '联系人',
        span: 12
      },
      {
        label: '归属企业',
        prop: 'parentId',
        placeholder: '归属企业',
        span: 12
      },
      {
        label: '归属公司',
        prop: 'orgId',
        placeholder: '归属公司',
        span: 12,
        display: userStore.user.orgId == '484'
      },
      {
        label: '归属人员',
        prop: 'userId',
        span: 12
      }
    ]
  },
  dialogObj: {
    visible: false,
    title: '',
    width: '50%',
    model: '',
    type: {
      task: { title: '新建任务', width: '40%' },
      pool: { title: '转入公海', width: '40%' },
      receive: {
        title: '确认提示',
        width: '30%'
      }
    }
  },
  selectionData: [],
  dialogParam: {}, //弹窗组件配置
  selectOptionObj: {}, // select
  followUpParam: {} //跟进
})
const {
  updateTime,
  queryForm,
  tableData,
  queryFormOption,
  drawerFormOption,
  dialogObj,
  selectionData,
  dialogParam,
  selectOptionObj,
  total,
  followUpParam
} = toRefs(data)
const {
  customer_status,
  customer_class,
  customer_source,
  customer_star,
  industry_category
} = proxy.useDict(
  'customer_status',
  'customer_class',
  'customer_source',
  'customer_star',
  'industry_category'
)

const companyOptions = ref([])
const parentOptions = ref([])
const statusDescription = ref('') //移入公海状态备注

/**
 * 所属企业模糊搜索
 * @param val 当前输入的值
 */
function queryCustomer(val) {
  let params = {
    pageNum: 1,
    pageSize: 10,
    customerNameOrNumber: val
  }
  getCustomerList(params).then(res => {
    parentOptions.value = res.data.records
  })
}

/**
 * 弹窗选取获取选中的值
 * @param val
 *  type 业务类型
 *     selectData 选中的数据[{value: 1, label: '王晓易', $treeNodeId: 2}]
 *     labelData 选中的数据label ['王晓易']
 *     defaultCheckedKeys 选中的数据id [1]
 *     dialogVisible: false 弹出框的关闭
 */
function selectData(val) {
  console.info('val', val)
  //归属人员
  if (val.type == 'userId') {
    if (!val.selectData.length) {
      queryForm.value[val.type] = ''
    } else {
      selectOptionObj.value[val.type] = val.selectData
      queryForm.value[val.type] = val.defaultCheckedKeys[0]
    }
  }
}

/**
 * 弹窗保存
 */
function dialogSave() {
  switch (dialogObj.value.model) {
    case 'receive': //领取
      const array = selectionData.value.map(item => {
        return {
          statusDescription: '',
          id: item.id,
          status: '2',
          userId: userStore.user.userId,
          userName: userStore.user.nickName
        }
      })
      updateForOpenSea(array).then(res => {
        proxy.$modal.msgSuccess(res.msg)
        handleCloseDialog()
        getList()
      })
      break
  }
}

/**
 * 归属人员input获取焦点事件
 */
function userInputFocus() {
  dialogParam.value.type = 'userId'
  dialogParam.value.title = '选择归属人员'
  dialogParam.value.dataType = 'person'
  dialogParam.value.multiple = false
  dialogParam.value.checkStrictly = false
  dialogParam.value.nodeKey = 'id'
  dialogParam.value.apiParams = { deptId: queryForm.value.orgId }

  selectOptionObj.value['userId'] = []

  // 有默认值
  if (queryForm.value['userId'] && queryForm.value['userId'].length) {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = [queryForm.value['userId']]
  } else {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = []
  }
}

/**
 * 获取归属公司数据
 * @returns {Promise<void>}
 */
async function getCompany() {
  // 所属单位列表
  let response = await treeselect({ deptType: 1 })
  companyOptions.value = response.data
  if (userStore.user.orgId !== '484') {
    queryForm.value.orgId = userStore.user.orgId * 1
  }

  getList()
}

/**
 * 获取客户列表
 */
function getList() {
  loading.value = true
  console.info('userStore', updateTime.value)
  let params = JSON.parse(JSON.stringify(queryForm.value))
  if (updateTime.value != null && updateTime.value.length > 0) {
    params.updateTimeStart = updateTime.value[0] + ' 00:00:00'
    params.updateTimeEnd = updateTime.value[1] + ' 23:59:59'
  } else {
    params.updateTimeStart = undefined
    params.updateTimeEnd = undefined
  }

  delete params.updateTime
  console.info('params', params)
  getCustomerList(params)
    .then(res => {
      if (res.data != null) {
        tableData.value = res.data.records
        total.value = res.data.total
      } else {
        tableData.value = []
        total.value = 0
      }
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 弹窗关闭
 */
function handleCloseDialog() {
  dialogObj.value.visible = false
}

/**
 * 弹窗开启操作
 * @param type 弹窗组件类型
 *
 */
function handleOpenDialog(type) {
  if (type == 'receive') {
    console.info('selectionData.value', selectionData)
    if (!selectionData.value.length) {
      proxy.$modal.msgWarning('请选择数据')
      return
    }
  }

  dialogObj.value.title = dialogObj.value.type[type].title
  dialogObj.value.width = dialogObj.value.type[type].width
  dialogObj.value.model = type
  dialogObj.value.visible = true
}

/**
 * 表格多选
 */
function handleSelectionChange(val) {
  selectionData.value = val
  console.info('selectionData', selectionData)
}

/**
 * 查询
 */
function handleQuery() {
  queryForm.value.pageNum = 1
  getList()
}

/**
 * 跳转详情
 * @param row 行数据
 */
function goDetails(row) {
  router.push({
    path: '/customerManage/customerModules/customerDetails',
    query: { customerId: row.id }
  })
}

/**
 * 初始化
 */
function init() {
  // 获取归属公司数据
  getCompany()
}

init()

/**
 * 打开高级筛选抽屉
 */
function openDrawer() {
  drawer.value = true
}

/**
 * 重置
 */
async function handleEmpty() {
  updateTime.value = []
  proxy.$refs.queryFormRef.resetFields()
  queryForm.value = {
    pageNum: 1,
    pageSize: 10,
    status: '8',
    orgId: userStore.user.orgId,
    customerNameOrNumber: '',
    phoneAndNameContact: ''
  }

  // queryForm.value.orgId = userStore.user.orgId
  await getList()
}

/**
 * 高级筛选清空
 * @returns {Promise<void>}
 */
async function handleDrawerFormEmpty() {
  updateTime.value = []
  proxy.$refs.drawerFormRef.resetFields()
  queryForm.value = {
    pageNum: 1,
    pageSize: 10,
    status: '8',
    customerNameOrNumber: '',
    phoneAndNameContact: '',
    orgId: userStore.user.orgId
  }

  // queryForm.value.orgId = userStore.user.orgId * 1
  await getList()
}
</script>

<style scoped lang="scss">
.customerList {
  .el-drawer .avue-form {
    @apply p-0;
  }
}
</style>
